﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using LCUV;
using System.Text;

namespace sWarranty.WEB
{
    public partial class SOMSerialMgrByW : System.Web.UI.Page
    {
        public string _currentUserEmpNo = "";
        public string _currentUserAuthority = "";
        public string _currentUserRegion = "";

        //page nay chua xet theo curUserRegion

        protected void Page_Load(object sender, EventArgs e)
        {

            _currentUserEmpNo = GetUserLoginEmpNo();
            Session["UrltoFw"] = "SOMSerialMgrByW.aspx";

            if (_currentUserEmpNo == "")
                Response.Redirect("login.aspx");
            if (!IsPostBack)
            {

                LoadAU();
                txtToDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
                int dateTOShow = 0 - Convert.ToInt32(DateTime.Now.DayOfWeek) + 1; //hom nay thu dateTOShow, thi chi hien den cot D dateTOShow
                txtFromDate.Text = DateTime.Now.AddDays(dateTOShow).ToString("MM/dd/yyyy");
            }

        }
        protected string GetUserLoginEmpNo()
        {
            string t = "";
            try
            {
                if (Session["UserLoginInfo"] != null)
                {
                    Entities db = new Entities();
                    var u = (TB_USER[])Session["UserLoginInfo"];
                    int _UID = Convert.ToInt32(u.Single().ID);
                    var au = from ft in db.TB_USER_LEVEL
                             where ft.USER_ID == _UID
                             select ft;
                    int _le = Convert.ToInt32(au.Single().LEVEL_ID);
                    var le = from xx in db.TB_LEVEL
                             where xx.ID == _le
                             select xx;
                    _currentUserAuthority = le.Single().REMARK;
                    _currentUserRegion = u.Single().REGION_ID;
                    if (_currentUserRegion != "00")
                    {
                        DBAction.SetSelected(dropRegion, DBAction.GetRegionByID(u.Single().REGION_ID));
                        dropRegion.Enabled = false;
                    }
                    return u.Single().EMPNO;
                }
            }
            catch (Exception)
            {
                t = "";
            }
            return t;
        }
        protected void LoadAU()
        {
            Entities db = new Entities();
            var au = (from t in db.TB_CM_MODEL_CAT
                      select new { au = t.PROD_L1 }).Distinct();
            ListItem i = new ListItem();
            i.Value = "0";
            i.Text = "Select";
            dropAu.Items.Add(i);
            au = au.OrderBy(k => k.au);
            foreach (var item in au)
            {
                i = new ListItem();
                i.Value = item.au;
                i.Text = item.au.ToUpper();
                dropAu.Items.Add(i);
            }
        }
        protected void BuildTable(DateTime from, DateTime to, string p_shop_name,
            string p_prod_l1, string p_model, string curUserRegion, string region)
        {
            DataTable dt = new DataTable();
            dt = DBAction.runStore("PK_SOM_MST.PR_SO_WKL_QTY_INQ", "uiroi", "p_ws_date", from.ToString("yyyyMMdd"), "p_we_date", to.ToString("yyyyMMdd"),
                 "p_shop_name", p_shop_name, "p_product", p_prod_l1,
                "p_model", p_model, "p_user_region", curUserRegion, "p_region", region,
                null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
            try
            {
                if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                {
                    MessageBox.Show(dt.Rows[0]["Error"].ToString());
                    return;
                }
            }
            catch (Exception)
            {
                //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            }
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }
        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "var btn=document.getElementById('btnFind');btn.click();", true);
            string region = "%";
            DateTime from = Convert.ToDateTime(txtFromDate.Text);
            DateTime to = Convert.ToDateTime(txtToDate.Text);
            string p_shop_name = null;
            string p_prod_l1 = "%";
            string p_model = null;

            if (dropRegion.SelectedValue != "00")
                region = dropRegion.SelectedValue;
            if (!string.IsNullOrEmpty(txtShopName.Text))
                p_shop_name = txtShopName.Text.Trim();
            if (dropAu.SelectedValue != "0")
                p_prod_l1 = dropAu.SelectedValue;
            if (!string.IsNullOrEmpty(txtModel.Text))
                p_model = txtModel.Text.Trim();

            DataTable dt = new DataTable();
            dt = DBAction.runStore("PK_SOM_MST.PR_SO_WKL_QTY_INQ", "uiroi", "p_ws_date", from.ToString("yyyyMMdd"), "p_we_date", to.ToString("yyyyMMdd"),
                 "p_shop_name", p_shop_name, "p_product", p_prod_l1,
                "p_model", p_model, "p_user_region", _currentUserRegion, "p_region", region,
                null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
            try
            {
                if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                {
                    MessageBox.Show(dt.Rows[0]["Error"].ToString());
                    return;
                }
            }
            catch (Exception)
            {
                //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            }
            RadGrid1.DataSource = dt;
        }
        protected void btnFind_Click(object sender, EventArgs e)
        {
            string region = "%";
            DateTime from = Convert.ToDateTime(txtFromDate.Text);
            DateTime to = Convert.ToDateTime(txtToDate.Text);
            string p_shop_name = null;
            string p_prod_l1 = "%";
            string p_model = null;

            if (dropRegion.SelectedValue != "00")
                region = dropRegion.SelectedValue;
            if (!string.IsNullOrEmpty(txtShopName.Text))
                p_shop_name = txtShopName.Text.Trim();
            if (dropAu.SelectedValue != "0")
                p_prod_l1 = dropAu.SelectedValue;
            if (!string.IsNullOrEmpty(txtModel.Text))
                p_model = txtModel.Text.Trim();

            BuildTable(from, to, p_shop_name, p_prod_l1, p_model, _currentUserRegion, region);
        }
        protected void RadGrid1_GroupsChanging(object sender, GridGroupsChangingEventArgs e)
        {
            if (e.Action == GridGroupsChangingAction.Group)
                RadGrid1.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = false;
            else
                if (e.Action == GridGroupsChangingAction.Ungroup)
                    RadGrid1.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = true;
        }

        protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if (e.Column is GridBoundColumn)
            {
                (e.Column as GridBoundColumn).DataFormatString = "<nobr>{0}</nobr>"; //auto width
                (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Center; 
                (e.Column as GridBoundColumn).HeaderStyle.Font.Bold = true; 

                //if ((e.Column as GridBoundColumn).HeaderText == "REGION")
                //    if (_currentUserRegion != "00")
                //        (e.Column as GridBoundColumn).Visible = false;
                if ((e.Column as GridBoundColumn).HeaderText == "NON_INCENTIVE" || (e.Column as GridBoundColumn).HeaderText == "INCENTIVE" || (e.Column as GridBoundColumn).HeaderText == "QTY" || (e.Column as GridBoundColumn).HeaderText == "AMT")
                {
                  //  (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                }
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.ExportSettings.FileName = "data";
            RadGrid1.MasterTableView.ExportToExcel();
            //string region = "%";
            //DateTime from = Convert.ToDateTime(txtFromDate.Text);
            //DateTime to = Convert.ToDateTime(txtToDate.Text);
            //string p_shop_name = null;
            //string p_prod_l1 = "%";
            //string p_model = null;

            //if (dropRegion.SelectedValue != "00")
            //    region = dropRegion.SelectedValue;
            //if (!string.IsNullOrEmpty(txtShopName.Text))
            //    p_shop_name = txtShopName.Text.Trim();
            //if (dropAu.SelectedValue != "0")
            //    p_prod_l1 = dropAu.SelectedValue;
            //if (!string.IsNullOrEmpty(txtModel.Text))
            //    p_model = txtModel.Text.Trim();

            //DataTable dt = new DataTable();
            //dt = DBAction.runStore("PK_SOM_MST.PR_SO_WKL_QTY_INQ", "uiroi", "p_ws_date", from.ToString("yyyyMMdd"), "p_we_date", to.ToString("yyyyMMdd"),
            //     "p_shop_name", p_shop_name, "p_product", p_prod_l1,
            //    "p_model", p_model, "p_user_region", _currentUserRegion, "p_region", region,
            //    null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
            //try
            //{
            //    if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
            //    {
            //        MessageBox.Show(dt.Rows[0]["Error"].ToString());
            //        return;
            //    }
            //}
            //catch (Exception)
            //{
            //    Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            //}
            //if (dt.Rows.Count > 0)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
            //                                      Select(column => column.ColumnName);
            //    sb.AppendLine(string.Join(",", columnNames));
            //    foreach (DataRow row in dt.Rows)
            //    {
            //        IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
            //        sb.AppendLine(string.Join(",", fields));
            //    }

            //    Response.Clear();
            //    Response.Buffer = true;

            //    Response.AddHeader("content-disposition", "attachment;filename=SOM_W.xls");
            //    Response.ContentType = "application/ms-excel";
            //    Response.Charset = "";
            //    Response.ContentEncoding = System.Text.Encoding.Unicode;
            //     Response.ContentType = "application/text";
            //    Response.Output.Write(sb.ToString());
            //    Response.Flush();
            //    Response.End();
            //}
            //else
            //{
            //    MessageBox.Show("There are no data");
            //}
        }
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (_currentUserRegion != "00")
            {
                GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("REGION");
                if (column != null)
                {
                    column.Visible = false;
                }
            }
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                item["AMT"].Text = String.Format("{0:#,0}", item["AMT"].Text);
            }

        }

    }
}